//
//  WXPAuthKTPVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/27.
//
//

#import "WXPAuthKTPVC.h"
#import "WXPAuthKTPContentView.h"
#import "WXPKTPTakePictureVC.h"
#import "WXPKTPHintFooterView.h"

@interface WXPAuthKTPVC ()

@property (nonatomic, strong) WXPAuthKTPContentView * viewContent;
@property (nonatomic, strong) WXPKTPHintFooterView * footerView;
@property (nonatomic, assign) BOOL isRetake;
@property (nonatomic, assign) NSInteger ktpFailNumber; // KTP认证失败次数
@property (nonatomic,   copy) NSString * imageUrl;
@property (nonatomic, assign) BOOL photoORCSuccess;

@end

@implementation WXPAuthKTPVC

#pragma mark - lazy
- (WXPAuthKTPContentView *)viewContent{
    if (!_viewContent) {
        _viewContent = [WXPAuthKTPContentView new];
        [_viewContent.IDCardInputView.tfNumber addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
        [_viewContent.IDCardInputView.tfName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
        _viewContent.IDCardInputView.tfName.delegate = self;
        _viewContent.IDCardInputView.tfNumber.delegate = self;
        WEAKSELF
        _viewContent.blockResetHeaderView = ^{
            [weakSelf resetHeaderView];
        };
        _viewContent.cameraView.blockTakePhoto = ^{
            if(weakSelf.ktpFailNumber < 0){
                // 第一次显示弹窗引导
                weakSelf.ktpFailNumber = 0;
                [weakSelf.viewContent.cameraView showExamplePopupView];
            }else{
                // 不是第一次，失败次数每满2次时，再点击KTP拍照时展示一次
                NSInteger failNumber = weakSelf.ktpFailNumber;
                if(failNumber > 0 && failNumber%2==0){
                    weakSelf.ktpFailNumber = 0;
                    [weakSelf.viewContent.cameraView showExamplePopupView];
                }else{
                    // 去拍照
                    [weakSelf requestAuthCheckWithAuthType];
                }
            }
        };
        _viewContent.cameraView.examplePopupView.blockEnsure = ^{
            // 去拍照
            [weakSelf requestAuthCheckWithAuthType];
        };
//        _viewContent.blockResetAuthBtn = ^(BOOL clickable) {
//            weakSelf.btnAuth.alpha = clickable ? 1 : 0.5;
//            weakSelf.btnAuth.userInteractionEnabled = clickable;
//        };
    }
    return _viewContent;
}
- (WXPKTPHintFooterView *)footerView
{
    if (_footerView == nil) {
        _footerView = [WXPKTPHintFooterView  new];
    }
    return  _footerView;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Page action:KEY_ENTER type:KEY_page];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Page action:KEY_OUT type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.photoORCSuccess = false;
    self.ktpFailNumber = -1;
    [self.navView resetViewWithTitle:@"KTP"];
    [self.progressView resetViewWithNum:@"2"];
    [self.progressView.moneyView resetViewWithTag:1];
    [self resetHeaderView];
    [self resetFooterView];
    WEAKSELF
    [self.btnAuth setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
        [NSObject clickFeedback];
        [weakSelf.btnAuth addClickAnimate];
        [weakSelf requestSubmitAuth];
    }];
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.progressView,
        [GlobalMethod getViewWithHeight:16],
        self.viewContent,
    ]];
    self.tableView.tableHeaderView = self.headerView;
}
- (void)resetFooterView{
    UIView * view = [UIView initWithViews:@[
        self.footerView,
    ]];
    self.tableView.tableFooterView = view;
}

// 跳转去拍照
- (void)jumpToTakePicture{
    WEAKSELF
    WXPKTPTakePictureVC * vc = [WXPKTPTakePictureVC new];
    vc.isIDFrontRetake = self.isRetake;
    if(self.isRetake==false){
        // 没做过ocr时的点击拍照
        
    }else{
        // 拍摄后不管失败还是成功，用户再次点击拍摄就打此点
         [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_ID_Front_Retake action:KEY_BUTTON_CLICK type:KEY_button];
    }
    // 返回认证图片
    vc.blockImage = ^(UIImage *image, BOOL isSuccess, BOOL isRetake) {
        // 不需要显示
        weakSelf.isRetake = isRetake;
        // weakSelf.idCardEscanearView.markImage.image = image;
        // 是否认证成功
        if(isSuccess){
            weakSelf.photoORCSuccess = true;
            [weakSelf.viewContent.cameraView resetViewWithShowSuccess:image];
            [weakSelf.viewContent resetAuthKTPContentViewWithIsSuccess:true];
        }else{
            weakSelf.photoORCSuccess = false;
            [weakSelf.viewContent resetAuthKTPContentViewWithIsSuccess:false];
            NSInteger failNumber = weakSelf.ktpFailNumber;
            weakSelf.ktpFailNumber = failNumber + 1;
            [weakSelf.viewContent.cameraView resetViewWithShowFail:image];
        }
    };
    // 认证信息
    vc.blockIdentityInformation = ^(NSDictionary * dataDic) {
         [weakSelf showIDCardInfor:dataDic];
    };
    // 认证失败
    vc.blockAuthFail = ^{
        weakSelf.photoORCSuccess = false;
        [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Result extInfo:@{@"name": @"", @"idNum": @"", @"isSuccess": [NSNumber numberWithBool:false]}];
        weakSelf.viewContent.IDCardInputView.tfName.text = @"";
        weakSelf.viewContent.IDCardInputView.tfNumber.text = @"";
        [weakSelf.footerView resetViewWithShowHint:false];
        [weakSelf resetFooterView];
        [weakSelf resetEntregarBtn];
    };
    self.startTime = [GlobalMethod getTimeStampMillisecond];
    [Global_Nav pushViewController:vc animated:true];
}

// 获取填充认证信息
- (void)showIDCardInfor:(NSDictionary *)dataDic{
    self.imageUrl = [dataDic stringValueForKey:KEY_url];
    NSDictionary * entity = [dataDic dictionaryValueForKey:KEY_tongDunOCRResponseEntity];
    NSDictionary * idCardData = [entity dictionaryValueForKey:KEY_idCardData];
    self.viewContent.IDCardInputView.tfName.text = [idCardData stringValueForKey:KEY_fullName];
    self.viewContent.IDCardInputView.tfNumber.text = [idCardData stringValueForKey:KEY_idNumber];
    // 打点
    [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Name_Input action:KEY_INPUT type:KEY_input];
    [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_IdNo_Input action:KEY_INPUT type:KEY_input];
    [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Result extInfo:@{@"name": self.viewContent.IDCardInputView.tfName.text, @"idNum": self.viewContent.IDCardInputView.tfNumber.text, @"isSuccess": [NSNumber numberWithBool:YES]}];
    [self.footerView resetViewWithShowHint:isStr(self.viewContent.IDCardInputView.tfNumber.text)];
    [self resetFooterView];
    
    [self resetEntregarBtn];
    // 风控埋点
    [GlobalMethod addRiskControlWithType:KEY_ID_CARD_FRONT startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
}

- (void)resetEntregarBtn{
    BOOL nameOnlySpace = [self.viewContent.IDCardInputView.tfName.text isOnlyBlankSpace];
    BOOL numOnlySpace = [self.viewContent.IDCardInputView.tfNumber.text isOnlyBlankSpace];
    if(isStr(self.viewContent.IDCardInputView.tfName.text) && isStr(self.viewContent.IDCardInputView.tfNumber.text) && nameOnlySpace==false && numOnlySpace==false && self.photoORCSuccess == true){
        self.btnAuth.alpha = 1;
        self.btnAuth.userInteractionEnabled = true;
    }else{
        self.btnAuth.alpha = 0.5;
        self.btnAuth.userInteractionEnabled = false;
    }
}

#pragma mark - textField
- (void)textFieldDidChange:(UITextField *)textField{
    if(textField == self.viewContent.IDCardInputView.tfNumber){
        [self.footerView resetViewWithShowHint:isStr(textField.text)];
        [self resetFooterView];
    }
    [self resetEntregarBtn];
}
// 获得焦点
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if(textField == self.viewContent.IDCardInputView.tfName){
        [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Name_Input action:KEY_GET_FOCUS type:KEY_input];
    }
    if(textField == self.viewContent.IDCardInputView.tfNumber){
        // 打点
        [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_IdNo_Input action:KEY_GET_FOCUS type:KEY_input];
    }
}
// 失去焦点
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if(textField == self.viewContent.IDCardInputView.tfName){
        [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Name_Input action:KEY_LOST_FOCUS type:KEY_input];
    }
    if(textField == self.viewContent.IDCardInputView.tfNumber){
        [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_IdNo_Input action:KEY_LOST_FOCUS type:KEY_input];
    }
}

// 粘贴行为
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if(textField == self.viewContent.IDCardInputView.tfName){
        if (isStr(string)) {
            [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Name_Input action:KEY_INPUT type:KEY_input];
        }
    }
    if(textField == self.viewContent.IDCardInputView.tfNumber){
        if (isStr(string)) {
            [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_IdNo_Input action:KEY_INPUT type:KEY_input];
        }
    }
    // 检测是否为粘贴行为
    NSString * trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([UIPasteboard generalPasteboard].string.length > 0 && [trimmedString isEqualToString:[UIPasteboard generalPasteboard].string]) {
        if(textField == self.viewContent.IDCardInputView.tfName){
            [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_Name_Input action:KEY_PARSE type:KEY_input];
        }
        if(textField == self.viewContent.IDCardInputView.tfNumber){
            [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_IdNo_Input action:KEY_PARSE type:KEY_input];
        }
        return true;
    }
    return YES;
}


#pragma mark - request
// 检查用户是否可以做某项授权接口
- (void)requestAuthCheckWithAuthType{
    [RequestApi requestCheckUserCanAuthWithType:KEY_ADVANCEOCR phone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        if([response boolValueForKey:KEY_checkResult]){
            // 当接口返回‘true’时，跳转KTP拍照页面进行拍照，先验证相机权限
            WEAKSELF
            [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                [GlobalMethod mainQueueBlock:^{
                    if (granted){
                        [weakSelf jumpToTakePicture];
                    }
                }];
            }];
        }else{
            // 当接口返回‘false’时，弹窗提示
            [GlobalMethod showAlert:@"Lo sentimos. Aún no es la fecha del evento"];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 提交认证
- (void)requestSubmitAuth{
    [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_Save_Start extInfo:nil];
    NSDictionary * dic = @{
        KEY_idNo: [self.viewContent.IDCardInputView.tfNumber.text removeHeadAndTailSpace],
        KEY_realName: [self.viewContent.IDCardInputView.tfName.text removeHeadAndTailSpace],
        KEY_ossIdCardPositiveImg: readStr(self.imageUrl),
    };
    [RequestApi requestSaveUserInfoWithData:dic step:KEY_IDENTITY_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
         [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_Save_End extInfo:@{@"idNum":self.viewContent.IDCardInputView.tfNumber.text, @"isSuccess": [NSNumber numberWithBool:YES]}];
        // [self requestAuthLivenConfig];
        
        // 调用获取下一步接口，跳转到该接口返回的对应认证页面
        [self requestGetNextStep];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 获取活体渠道接口
- (void)requestAuthLivenConfig{
    [RequestApi requestNewAuthLivenConfigWithPhone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {

        if([response boolValueForKey:KEY_skipLiven]){
            // 返回的skipLiven为true时需要进行一次保存，保存时data为空对象{}
            [self requestSaveUserInfo];
        }else{
            // 调用获取下一步接口，跳转到该接口返回的对应认证页面
            [self requestGetNextStep];
        }

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {

    }];
}
// 保存用户信息
- (void)requestSaveUserInfo{
    [RequestApi requestSaveUserInfoWithData:@{} step:KEY_LIVENESS_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {

        // [GlobalMethod userBehaviorRecordWithPageName:@"VerifyFacial" action:@"Save_End" extInfo:nil];
        // [GlobalMethod showAlert:@"¡Verificación exitosa! "];
        // 等一秒钟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 在这里放置需要延迟执行的代码
            // NSLog(@"等待了1秒钟");
            // 风控埋点
            [GlobalMethod addRiskControlWithType:KEY_LIVE_OCR startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
            // 获取下一步
            [self requestGetNextStep];
        });

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        NSLog(@" --- error --- %@", errorStr);
    }];
}

@end
